package com.aizhixin.lab.task.service;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.company.entity.Classes;
import com.aizhixin.lab.company.service.ClassesService;
import com.aizhixin.lab.statistics.util.ReportUtils;
import com.aizhixin.lab.task.core.ExerciseType;
import com.aizhixin.lab.task.domain.*;
import com.aizhixin.lab.task.entity.*;
import com.aizhixin.lab.task.repository.TaskStuCodeRepository;
import com.aizhixin.lab.task.repository.TaskStuStatisticsRepository;
import lombok.extern.slf4j.Slf4j;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.poi.ss.formula.functions.Rank;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.task.core.TaskInforCode;
import com.aizhixin.lab.task.repository.TaskStuInforRepository;

@Slf4j
@Service
@Transactional
public class TaskStuInforService {
    @Autowired
    private TaskStuInforRepository taskStuInforRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private TaskFileService taskFileService;
    @Autowired
    private ReleaseTaskService releaseTaskService;
    @Autowired
    private ReleaseTaskQuestionsService releaseTaskQuestionsService;
    @Autowired
    private ReleaseTaskQuestionChoiceService releaseTaskQuestionChoiceService;
    @Autowired
    private ReleaseTaskFileService releaseTaskFileService;
    @Autowired
    private TaskStuAnswerService taskStuAnswerService;
    @Autowired
    private TaskStuFileService taskStuFileService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private TaskStuCodeRepository taskStuCodeRepository;
    @Autowired
    private TaskStuStatisticsRepository statisticsRepository;

    @Autowired
    private TaskStuStatisticsRepository taskStuStatisticsRepository;

    public TaskStuInfor save(TaskStuInfor stu) {
        return taskStuInforRepository.save(stu);
    }

    public void saveList(List<TaskStuInfor> stu) {
        taskStuInforRepository.save(stu);
    }

    public TaskStuInfor findById(String taskStuInforId) {
        return taskStuInforRepository.findOne(taskStuInforId);
    }

    RowMapper<StuTaskInforDomain> taskRm = new RowMapper<StuTaskInforDomain>() {

        @Override
        public StuTaskInforDomain mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            StuTaskInforDomain domain = new StuTaskInforDomain();
            domain.setId(rs.getString("id"));
            domain.setCourseName(rs.getString("course_name"));
            domain.setTaskName(rs.getString("TASK_NAME"));
            domain.setCreatedDate(rs.getTimestamp("CREATED_DATE"));
            domain.setCommitTime(rs.getTimestamp("commit_time"));
            domain.setReleaseTaskId(rs.getString("release_task_id"));
            domain.setResult(rs.getString("result"));
            domain.setTaskStatus(rs.getString("task_status"));
            return domain;
        }
    };

    public <T> Map<String, Object> findTaskPage(QueryTaskDomain domain) {

        String querySql = "select tsi.id,tsi.release_task_id,rt.TASK_NAME,c.`name` as course_name,tsi.task_status,tsi.result,tsi.created_date,tsi.commit_time  from `t_task_stu_infor` tsi LEFT JOIN `t_release_task` rt ON tsi.release_task_id = rt.id LEFT JOIN `c_course` c ON c.id = rt.COURSE_ID where rt.DELETE_FLAG =0 and tsi.delete_flag =0 and c.delete_flag =0  ";
        String countSql = "select count(*) from `t_task_stu_infor` tsi LEFT JOIN `t_release_task` rt ON tsi.release_task_id = rt.id LEFT JOIN `c_course` c ON c.id = rt.COURSE_ID where rt.DELETE_FLAG =0 and tsi.delete_flag =0 and c.delete_flag =0 ";

        if (!StringUtils.isEmpty(domain.getCourseId())) {
            querySql += " and rt.COURSE_ID='" + domain.getCourseId() + "'";
            countSql += " and rt.COURSE_ID='" + domain.getCourseId() + "'";
        }
        if (!StringUtils.isEmpty(domain.getTaskStatus())) {
            querySql += " and tsi.task_status='" + domain.getTaskStatus() + "'";
            countSql += " and tsi.task_status='" + domain.getTaskStatus() + "'";
        }
//			if (!StringUtils.isEmpty(domain.getName())) {
//				querySql += " and u.NAME like '%" + domain.getName() + "%'";
//				countSql += " and u.NAME like '%" + domain.getName() + "%'";
//			}

        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("tsi.CREATED_DATE");
        dto.setAsc(false);
        sort.add(dto);

        return pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), taskRm, sort, querySql,
                countSql);
    }


    RowMapper<StuTaskDomain> taskStu = new RowMapper<StuTaskDomain>() {

        @Override
        public StuTaskDomain mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            StuTaskDomain domain = new StuTaskDomain();
            domain.setId(rs.getString("id"));
            domain.setCourseName(rs.getString("course_name"));
            domain.setTaskName(rs.getString("TASK_NAME"));
            domain.setCreateDate(rs.getDate("created_date"));
            domain.setCourseChapterName(rs.getString("course_chapter_name"));
            domain.setCourseMinutiaName(rs.getString("course_minutia_name"));
            domain.setQuestionNum(rs.getInt("question_num"));
            domain.setTaskStatus(rs.getString("task_status"));
            domain.setTaskResult(rs.getString("result"));
            return domain;
        }
    };

    /**
     * 学生查询个人任务列表
     *
     * @param domain
     * @param <T>
     * @return
     */
    public <T> Map<String, Object> findTasksPage(QueryTaskDomain domain, Long stuId) {

        String querySql = "SELECT tts.id , trt.TASK_NAME task_name , cc.`name` course_name, ccc1.`name` course_chapter_name , ccc2.`name` course_minutia_name,trt.CREATED_DATE created_date, tts.task_status task_status,trt.QUESTIONS_NUM question_num,tts.result result FROM t_task_stu_infor tts LEFT JOIN t_release_task trt ON tts.release_task_id = trt.ID LEFT JOIN c_course cc ON trt.COURSE_ID =cc.id LEFT JOIN c_course_chapter ccc1 ON trt.COURSE_CHAPTER_ID = ccc1.id LEFT JOIN c_course_chapter ccc2 ON trt.COURSE_MINUTIA_ID =ccc2.id WHERE tts.delete_flag = 0 ";
        String countSql = "SELECT count(*) FROM t_task_stu_infor tts LEFT JOIN t_release_task trt ON tts.release_task_id = trt.ID LEFT JOIN c_course cc ON trt.COURSE_ID =cc.id LEFT JOIN c_course_chapter ccc1 ON trt.COURSE_CHAPTER_ID = ccc1.id LEFT JOIN c_course_chapter ccc2 ON trt.COURSE_MINUTIA_ID =ccc2.id WHERE tts.delete_flag = 0  ";

        if (!StringUtils.isEmpty(domain.getCourseId())) {
            querySql += " and trt.COURSE_ID='" + domain.getCourseId() + "'";
            countSql += " and trt.COURSE_ID='" + domain.getCourseId() + "'";
        }
        if (!StringUtils.isEmpty(domain.getTaskStatus())) {
            querySql += " and tts.task_status='" + domain.getTaskStatus() + "'";
            countSql += " and tts.task_status='" + domain.getTaskStatus() + "'";
        }
        if (stuId > 0L && stuId != null) {
            querySql += " and tts.stu_id=" + stuId;
            countSql += " and tts.stu_id=" + stuId;
        }

        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("(CASE WHEN tts.task_status='uncommit' THEN 1 WHEN tts.task_status='pending' THEN 2 WHEN tts.task_status='approved' THEN 3 ELSE 4 END ),tts.created_date");
        dto.setAsc(false);
        sort.add(dto);
        return pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), taskStu, sort, querySql,
                countSql);
    }

    public void deleteReleaseTask(String releaseTaskId) {
        List<TaskStuInfor> stuInfors = taskStuInforRepository.findAllByReleaseTaskIdAndDeleteFlag(releaseTaskId, DataValidity.VALID.getState());
        for (int i = 0; i < stuInfors.size(); i++) {
            stuInfors.get(i).setDeleteFlag(1);
        }
        taskStuInforRepository.save(stuInfors);
    }

    /**
     * 获取任务当前状态如果未完成查看已做了多少题
     *
     * @param domainList
     * @return
     */
    public List<StuTaskDomain> getTaskStatus(List<StuTaskDomain> domainList) {
        List<StuTaskDomain> domains = new ArrayList<>();
        for (StuTaskDomain taskDomain : domainList) {
            StuTaskDomain taskDomain1 = new StuTaskDomain();
            BeanUtils.copyProperties(taskDomain, taskDomain1);
            String taskStatus = taskDomain.getTaskStatus();
            if (taskStatus.equals(TaskInforCode.TASK_STATUS_UNCOMMIT)) {
                Integer answerNum = taskStuAnswerService.getAnswerNum(taskDomain.getId());
                if (answerNum == 0) {
                    taskDomain1.setTaskStatus("未开始");
                } else {
                    taskDomain1.setTaskStatus(answerNum + "/" + taskDomain1.getQuestionNum());
                }
            } else if (taskStatus.equals(TaskInforCode.TASK_STATUS_PENDING)) {
                taskDomain1.setTaskStatus("已提交");
            } else if (taskStatus.equals(TaskInforCode.TASK_STATUS_APPROVED)) {
                taskDomain1.setTaskStatus("已点评");
            }
            domains.add(taskDomain1);
        }
        return domains;
    }
    public List<TaskStuQusetionsDomain> findStuTaskQuestionList(TaskStuInfor taskStuInfor) {

        ArrayList<TaskStuQusetionsDomain> domainList = new ArrayList<TaskStuQusetionsDomain>();
        List<ReleaseTaskQuestion> questionlist = releaseTaskQuestionsService
                .findByReleaseTaskIdOrderByOrderNumAsc(taskStuInfor.getReleaseTaskId());
        if (null != questionlist && questionlist.size() > 0) {
            List<String> qusetionIds = new ArrayList<>();
            for (ReleaseTaskQuestion question : questionlist) {
                qusetionIds.add(question.getId());
                TaskStuQusetionsDomain domain = new TaskStuQusetionsDomain();
                BeanUtils.copyProperties(question, domain);
                domainList.add(domain);
            }

            List<TaskStuAnswer> stuAnswerList = taskStuAnswerService
                    .findAllByTaskStuInforIdAndReleaseTaskId(taskStuInfor.getId(), taskStuInfor.getReleaseTaskId());
            List<ReleaseQuestionChoice> workQuestionsChoiceDomainList = releaseTaskQuestionChoiceService
                    .getChoiceList(qusetionIds);

            for (TaskStuQusetionsDomain item : domainList) {
                if (item.getQuestionType() == null) {
                    continue;
                }

                if (item.getQuestionType() == 10 || item.getQuestionType() == 20 || item.getQuestionType() == 30) {
                    List<ReleaseQuestionChoice> choicelist = new ArrayList<>();
                    for (ReleaseQuestionChoice workQuestionsChoiceDomain : workQuestionsChoiceDomainList) {
                        if (workQuestionsChoiceDomain.getReleaseQuestionId().equals(item.getId())) {
                            choicelist.add(workQuestionsChoiceDomain);
                        }
                    }
                    item.setChoicelist(choicelist);
                }

                List<ReleaseTaskFile> alist = releaseTaskFileService.findAllByTaskId(taskStuInfor.getReleaseTaskId());
                List<ReleaseTaskFile> qad = new ArrayList<>();
                List<ReleaseTaskFile> qadAnswer = new ArrayList<>();
                List<ReleaseTaskFile> qadAna = new ArrayList<>();
                for (int i = 0; i < alist.size(); i++) {
                    if (item.getId().equals(alist.get(i).getReleaseQuestionId())) {
                        if (alist.get(i).getSource().equals(TaskInforCode.FILE_FROM_QUESTION)) {
                            qad.add(alist.get(i));
                        }
                        if (alist.get(i).getSource().equals(TaskInforCode.FILE_FROM_ANSWER)) {
                            qadAnswer.add(alist.get(i));
                        }
                        if (alist.get(i).getSource().equals(TaskInforCode.FILE_FROM_ANALYSIS)) {
                            qadAna.add(alist.get(i));
                        }
                    }
                }
                item.setAccessorylist(qad);
                item.setAccessorylistAnswer(qadAnswer);
                item.setAccessorylistAna(qadAna);
                item.setBatchTime(taskStuInfor.getBatchTime());

                if (!TaskInforCode.TASK_STATUS_UNCOMMIT.equals(taskStuInfor.getTaskStatus())) {
                    // 查询学生答案
                    TaskStuAnswer stuAnswer = null;
                    for (TaskStuAnswer stu : stuAnswerList) {
                        if (item.getId().equals(stu.getReleaseQuestionId())) {
                            stuAnswer = stu;
                            break;
                        }
                    }
                    if (null != stuAnswer) {
                        if (!"".equals(stuAnswer.getStuAnswer()) && stuAnswer.getStuAnswer() != null) {
                            item.setStuAnswer(stuAnswer.getStuAnswer());
                        }
                        if (!"".equals(stuAnswer.getComment()) && stuAnswer.getComment() != null) {
                            item.setComment(stuAnswer.getComment());
                        }
                        if (!"".equals(stuAnswer.getRunResult()) && stuAnswer.getRunResult() != null) {
                            item.setRunResult(stuAnswer.getRunResult());
                        }
                        if (!"".equals(stuAnswer.getRunCode()) && stuAnswer.getRunCode() != null) {
                            item.setRunCode(stuAnswer.getRunCode());
                        }
                        // 查询学生答案附件列表
                        List<TaskStuFile> stuAnswerAList = taskStuFileService.findAllByStuIdAndReleaseTaskId(
                                taskStuInfor.getStuId(), taskStuInfor.getReleaseTaskId());
                        List<TaskStuFile> stuAccessList = new ArrayList<>();
                        for (int i = 0; i < stuAnswerAList.size(); i++) {
                            if (stuAnswerAList.get(i).getStuAnswerId().equals(stuAnswer.getId())) {
                                stuAccessList.add(stuAnswerAList.get(i));
                            }
                        }
                        if (stuAccessList != null) {
                            item.setStuAnswerAccessorylist(stuAccessList);
                        }

                    }
                }
            }

        }
        return domainList;
    }


    /**
     * 根据学生任务Id获取学生任务详情
     *
     * @param taskInforId
     * @return
     */
    public StuTaskDetailsDomain getStuTask(String taskInforId) {
        TaskStuInfor taskStuInfor = taskStuInforRepository.findById(taskInforId);
        ReleaseTask releaseTask = releaseTaskService.findById(taskStuInfor.getReleaseTaskId());
        StuTaskDetailsDomain stuTaskDetailsDomain = new StuTaskDetailsDomain();
        stuTaskDetailsDomain.setId(taskInforId);
        stuTaskDetailsDomain.setQuestionNum(releaseTask.getQuestionsNum());
        stuTaskDetailsDomain.setTaskName(releaseTask.getTaskName());
        stuTaskDetailsDomain.setCountDown(releaseTask.getCountDown());
        stuTaskDetailsDomain.setIsCountDown(releaseTask.getIsCountDown());
        List<ReleaseTaskQuestion> questionList = releaseTaskQuestionsService
                .findByReleaseTaskIdOrderByOrderNumAsc(taskStuInfor.getReleaseTaskId());
        ArrayList<TaskStuQusetionsDomain> domainList = new ArrayList<TaskStuQusetionsDomain>();
        if (null != questionList && questionList.size() > 0) {
            List<String> qusetionIds = new ArrayList<>();
            for (ReleaseTaskQuestion question : questionList) {
                qusetionIds.add(question.getId());
                TaskStuQusetionsDomain domain = new TaskStuQusetionsDomain();
                BeanUtils.copyProperties(question, domain);
                domain.setAnswer(null);
                if (question.getQuestionType().equals(ExerciseType.SINGLE.getIntValue()) || question.getQuestionType().equals(ExerciseType.MULTIPLE.getIntValue()) || question.getQuestionType().equals(ExerciseType.JUDGMENT.getIntValue())) {
                    List<ReleaseQuestionChoice> choiceList = releaseTaskQuestionChoiceService.getChoiceList(question.getId());
                    domain.setChoicelist(choiceList);
                }
                TaskStuAnswer taskAnswer = taskStuAnswerService.findTaskAnswer(question.getId(), taskInforId);
                if (taskAnswer != null) {
                    domain.setStuAnswer(taskAnswer.getStuAnswer());
                }
                List<ReleaseTaskFile> allByReleaseQuestionId = releaseTaskFileService.findAllByReleaseQuestionId(question.getId());
                List<TaskStuFile> taskStuFileList = taskStuFileService.findByReleaseQuestionIdAndStuId(question.getId(), taskStuInfor.getStuId());
                domain.setStuAnswerAccessorylist(taskStuFileList);
                domain.setAccessorylist(allByReleaseQuestionId);
                domainList.add(domain);
            }

        }
        stuTaskDetailsDomain.setTaskStuQusetionsDomainList(domainList);
        return stuTaskDetailsDomain;
    }

    public StuTaskReferenceCodeDomain findReferenceCode(String releaseQuestionId,String stuId) {
        StuTaskReferenceCodeDomain stuTaskReferenceCodeDomain = new StuTaskReferenceCodeDomain();
        ReleaseTaskQuestion releaseTask = releaseTaskQuestionsService.findReleaseTaskQuestion(releaseQuestionId);
        List<TaskStuCode> taskStuCodeList = taskStuCodeRepository.findByReleaseQuestionIdAndStuIdOrderBySubmitTimeDesc(releaseQuestionId,stuId);
        List<String> codeList = taskStuCodeList.stream().map(TaskStuCode::getSubmitCode).collect(Collectors.toList());
        stuTaskReferenceCodeDomain.setStuCode(codeList);
        stuTaskReferenceCodeDomain.setReferenceCode(releaseTask.getReferenceCode());
        return stuTaskReferenceCodeDomain;
    }

    public TaskStuStatistics findEvaluationData(String releaseQuestionId,String stuId) {
        TaskStuStatistics taskStuStatistics = taskStuStatisticsRepository.findByReleaseQuestionIdAndStuId(releaseQuestionId,stuId);
        return taskStuStatistics;
    }

    public StuTaskCodeEvaluatingDomain findCodeEvaluating(String releaseQuestionId,String stuId) {
        StuTaskCodeEvaluatingDomain stuTaskReferenceCodeDomain = new StuTaskCodeEvaluatingDomain();
        List<TaskStuCode> taskStuCodeList = taskStuCodeRepository.findByReleaseQuestionIdAndStuIdOrderBySubmitTimeDesc(releaseQuestionId,stuId);
        List<TaskStuCode> collect = taskStuCodeList.stream().sorted(Comparator.comparing(TaskStuCode::getSubmitTime)).collect(Collectors.toList());
        stuTaskReferenceCodeDomain.setCodeRow(collect.size() == 0 ? 0 : collect.get(0).getCodeRowNum());
        stuTaskReferenceCodeDomain.setErrorNum(collect.size() == 0 ? 0 : collect.get(0).getIsError() == null ? 0 : collect.get(0).getIsError());
        stuTaskReferenceCodeDomain.setSubmitCount(taskStuCodeList.size());
        stuTaskReferenceCodeDomain.setSubmitTime(collect.size() == 0 ? "" : collect.get(0).getSubmitTime().toString());
        return stuTaskReferenceCodeDomain;
    }

    public Integer[] findChartData(String releaseQuestionId,String stuId) {
        List<TaskStuCode> taskStuCodeList = taskStuCodeRepository.findByReleaseQuestionIdAndStuIdOrderBySubmitTime(releaseQuestionId,stuId);
        List<Integer> scoreList = new ArrayList<>();
        for (TaskStuCode score:taskStuCodeList) {
            scoreList.add(score.getScore());
        }
        //List<Integer> scoreList = taskStuCodeList.stream().map(TaskStuCode::getScore).collect(Collectors.toList());
        Integer[] scoreArray = scoreList.toArray(new Integer[scoreList.size()]);
        return scoreArray;
    }

    public StuTaskDetailsDomain findStuTask(String taskInforId) {
        StuTaskDetailsDomain stuTaskDetailsDomain = new StuTaskDetailsDomain();
        TaskStuInfor taskStuInfor = taskStuInforRepository.findById(taskInforId);
        ReleaseTask releaseTask = releaseTaskService.findById(taskStuInfor.getReleaseTaskId());
        stuTaskDetailsDomain.setId(taskInforId);
        stuTaskDetailsDomain.setQuestionNum(releaseTask.getQuestionsNum());
        stuTaskDetailsDomain.setTaskName(releaseTask.getTaskName());

        stuTaskDetailsDomain.setResult(taskStuInfor.getResult());

        stuTaskDetailsDomain.setComment(taskStuInfor.getComment());
        List<ReleaseTaskQuestion> questionList = releaseTaskQuestionsService
                .findByReleaseTaskIdOrderByOrderNumAsc(taskStuInfor.getReleaseTaskId());
        ArrayList<TaskStuQusetionsDomain> domainList = new ArrayList<TaskStuQusetionsDomain>();
        if (null != questionList && questionList.size() > 0) {
            for (ReleaseTaskQuestion question : questionList) {
                TaskStuQusetionsDomain domain = new TaskStuQusetionsDomain();
                BeanUtils.copyProperties(question, domain);
                if (question.getQuestionType().equals(ExerciseType.SINGLE.getIntValue()) || question.getQuestionType().equals(ExerciseType.MULTIPLE.getIntValue()) || question.getQuestionType().equals(ExerciseType.JUDGMENT.getIntValue())) {
                    List<ReleaseQuestionChoice> choiceList = releaseTaskQuestionChoiceService.getChoiceList(question.getId());
                    domain.setChoicelist(choiceList);
                    domain.setReferenceCode(question.getReferenceCode());
                }

                TaskStuAnswer taskAnswer = taskStuAnswerService.findTaskAnswer(question.getId(), taskInforId);
                if (taskAnswer != null) {
                    domain.setStuAnswer(taskAnswer.getStuAnswer());
                    domain.setRunCode(taskAnswer.getRunCode());
                }
                if ("hide".equals(taskStuInfor.getIsShowAnswer())) {
                    domain.setAnswer(null);
                }
                List<ReleaseTaskFile> allByReleaseQuestionId = releaseTaskFileService.findAllByReleaseQuestionId(question.getId());
                domain.setAccessorylist(allByReleaseQuestionId);
                domainList.add(domain);
            }

        }
        stuTaskDetailsDomain.setTaskStuQusetionsDomainList(domainList);
        return stuTaskDetailsDomain;
    }

    public FindTaskTopicDomain findProgrammeAndRubric(String releaseQuestionId,String releaseTaskId) {
        FindTaskTopicDomain findTaskTopicDomain = new FindTaskTopicDomain();
        ReleaseTaskQuestion taskStuInfor = releaseTaskQuestionsService.findReleaseTaskQuestion(releaseQuestionId);
        List<ReleaseTaskQuestion> releaseTaskQuestionList = releaseTaskQuestionsService.findByReleaseTaskIdAndQuestionTypeOrderByOrderNumAsc(releaseTaskId,60);
        findTaskTopicDomain.setQuestionNum(taskStuInfor.getQuestionContent());
        findTaskTopicDomain.setRestsTaskTopicDomainList(releaseTaskQuestionList);
        return findTaskTopicDomain;
    }

    public StuTaskQuestionListDomain autoJudgeAnswer(List<TaskStuQusetionsDomain> domains, TaskStuInfor infor) {
        StuTaskQuestionListDomain stuTaskQuestionListDomain = new StuTaskQuestionListDomain();
        Integer totalNum = 0;
        Integer errorNum = 0;
        Integer otherQuestionNum=0;
        Integer otherQuestionGrade=0;
        List<TaskStuQusetionsDomain> domainList = new ArrayList<>();
        List<TaskStuAnswer> taskStuAnswers = new ArrayList<>();
        for (TaskStuQusetionsDomain t : domains) {
            TaskStuAnswer taskAnswer = taskStuAnswerService.findTaskAnswer(t.getId(), infor.getId());
            if (t.getQuestionType() == 10) {
                totalNum++;
                if (null != taskAnswer) {
                    if (!StringUtils.isEmpty(t.getAnswer())&&t.getAnswer().equals(t.getStuAnswer())) {
                        taskAnswer.setIsCorrect(1);
                        t.setIsCorrect(1);
                        taskAnswer.setComment(100+"");
                    } else {
                        taskAnswer.setIsCorrect(0);
                        taskAnswer.setErrorType(1);
                        t.setIsCorrect(0);
                        t.setErrorType(1);
                        taskAnswer.setComment(0+"");
                        errorNum++;
                    }
                } else {
                    errorNum++;
                    t.setErrorType(3);
                }
            } else if (t.getQuestionType() == 20) {
                totalNum++;
                if (null != taskAnswer) {
                    if (t.getAnswer().equals(t.getStuAnswer())) {
                        taskAnswer.setIsCorrect(1);
                        t.setIsCorrect(1);
                        taskAnswer.setComment(100+"");
                    } else if (t.getAnswer().indexOf(t.getStuAnswer() == null ? "" : t.getStuAnswer()) > -1) {
                        taskAnswer.setIsCorrect(0);
                        taskAnswer.setErrorType(2);
                        t.setIsCorrect(0);
                        t.setErrorType(2);
                        taskAnswer.setComment(50+"");
                        errorNum++;
                    } else {
                        taskAnswer.setIsCorrect(0);
                        taskAnswer.setErrorType(1);
                        taskAnswer.setComment(0+"");
                        t.setIsCorrect(0);
                        t.setErrorType(1);
                        errorNum++;
                    }
                } else {
                    errorNum++;
                    t.setErrorType(3);
                }
            } else if (t.getQuestionType() == 30) {
                totalNum++;
                if (null != taskAnswer) {
                    if (t.getAnswer().equals(t.getStuAnswer())) {
                        taskAnswer.setIsCorrect(1);
                        t.setIsCorrect(1);
                        taskAnswer.setComment(100+"");
                    } else {
                        taskAnswer.setIsCorrect(0);
                        taskAnswer.setErrorType(0);
                        t.setIsCorrect(0);
                        t.setErrorType(0);
                        taskAnswer.setComment(0+"");
                        errorNum++;
                    }
                } else {
                    errorNum++;
                    t.setErrorType(3);
                }
            }else if (t.getQuestionType() ==40){
                totalNum++;
                try {
                    if (null != taskAnswer) {
                        if (t.getAnswer().contains(t.getStuAnswer())) {
                            taskAnswer.setIsCorrect(1);
                            t.setIsCorrect(1);
                            taskAnswer.setComment(100+"");
                        } else {
                            taskAnswer.setIsCorrect(0);
                            taskAnswer.setErrorType(0);
                            t.setIsCorrect(0);
                            t.setErrorType(0);
                            taskAnswer.setComment(0+"");
                            errorNum++;
                        }
                    } else {
                        errorNum++;
                        t.setErrorType(3);
                    }
                }catch (NullPointerException e){
                    errorNum++;
                    t.setErrorType(3);
                }

            }
            if (taskAnswer != null) {
                taskStuAnswers.add(taskAnswer);
                if (t.getQuestionType()==60){
                    TaskStuStatistics stuStatistics = statisticsRepository.findByReleaseQuestionIdAndStuId(t.getId(), taskAnswer.getStuId().toString());
                    if (!Objects.isNull(stuStatistics)){
                        t.setCodeAdvise(stuStatistics.getCodeAdvise());
                    }
                }
            }

            if (t.getQuestionType()!=10&&t.getQuestionType()!=20&&t.getQuestionType()!=30&&t.getQuestionType()!=40) {
                if (!Objects.isNull(taskAnswer)){
                    otherQuestionGrade+=ReportUtils.getScore(taskAnswer.getComment());
                    otherQuestionNum++;
                }else {
                    otherQuestionNum++;
                }
                domainList.add(t);
            }
        }

        stuTaskQuestionListDomain.setErrorNum(errorNum);
        stuTaskQuestionListDomain.setTotalNum(totalNum);
        if (infor.getTaskStatus().equals(TaskInforCode.TASK_STATUS_APPROVED)){
//            Double v = Double.parseDouble();

            stuTaskQuestionListDomain.setGrade(Double.valueOf(infor.getGrade()).intValue());
            stuTaskQuestionListDomain.setResult(infor.getResult());
        }else {
            if (otherQuestionNum == 0 && totalNum == 0) {
                stuTaskQuestionListDomain.setGrade(0);
            } else if (totalNum == 0) {

                stuTaskQuestionListDomain.setGrade((otherQuestionGrade / otherQuestionNum));
            } else if (otherQuestionNum == 0) {

                stuTaskQuestionListDomain.setGrade(((totalNum - errorNum) * 100 / totalNum));
            } else {
                stuTaskQuestionListDomain.setGrade(((totalNum == 0 ? 0 : (totalNum - errorNum) * 100 / totalNum) + otherQuestionGrade / otherQuestionNum) / 2);
            }
        }
        stuTaskQuestionListDomain.setResult(ReportUtils.getLevel(stuTaskQuestionListDomain.getGrade()));
        stuTaskQuestionListDomain.setIsShowAnswer(infor.getIsShowAnswer());
        stuTaskQuestionListDomain.setIsShowGrade(infor.getIsShowGrade());
        stuTaskQuestionListDomain.setTaskStuQusetionsDomainList(domainList);
        taskStuAnswerService.saveList(taskStuAnswers);

        return stuTaskQuestionListDomain;
    }

    public Map<String, Object> taskAvg(List<TaskStuQusetionsDomain> domains, TaskStuInfor infor) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer totalNum = 0;
        Integer sum = 0;

        for (TaskStuQusetionsDomain t : domains) {
            TaskStuAnswer taskAnswer = taskStuAnswerService.findTaskAnswer(t.getId(), infor.getId());

            if (t.getQuestionType() != 10 && t.getQuestionType() != 20 && t.getQuestionType() != 30) {
                totalNum++;
                if (null != taskAnswer) {
                    if (StringUtils.isEmpty(taskAnswer.getComment())) {
                        totalNum--;
                    } else {
                        sum += ReportUtils.getScore(taskAnswer.getComment());
                    }
                }
            }
        }
        if (totalNum == 0) {
            result.put(ApiReturnConstants.SUCCESS, Boolean.TRUE);
            result.put(ApiReturnConstants.DATA, "0");
            return result;
        }
        result.put(ApiReturnConstants.SUCCESS, Boolean.TRUE);
        result.put(ApiReturnConstants.DATA, sum / totalNum + "");
        return result;

    }


    public TaskStuInfor updateworkStuInfo(String workStuInfoId, String result, List<String> comment, List<String> id, boolean isAuto, String teacherName) {
        TaskStuInfor workStuInfo = findById(workStuInfoId);
        String workReleaseId = workStuInfo.getReleaseTaskId();
        List<TaskStuAnswer> stuAnswers = new ArrayList<>();
        List<TaskStuAnswer> stuAnswerList = taskStuAnswerService.findByIdIn(id);
        if (null != stuAnswerList) {
            for (int i = 0; i < id.size(); i++) {
                for (TaskStuAnswer stAnswer : stuAnswerList) {
                    if (stAnswer.getId().equals(id.get(i))) {
                        if (comment != null) {
                            if (comment.get(i) != null) {
                                stAnswer.setComment(comment.get(i));
                            }
                        }
                        stAnswer.setBatchTime(new Date());
                        stuAnswers.add(stAnswer);
                    }
                }
            }
        }
        if (!stuAnswers.isEmpty()) {
            taskStuAnswerService.saveList(stuAnswers);
        }
        Date date = new Date();
        workStuInfo.setBatchTime(date);
        ReleaseTask workRelease = releaseTaskService.findById(workReleaseId);
        if (workStuInfo.getResult() == null || "".equals(workStuInfo.getResult())) {
            Integer pendingNumber = workRelease.getPendingNum();
            if (pendingNumber == null) {
                pendingNumber = 0;
            }
            if (pendingNumber > 0) {
                workRelease.setPendingNum(pendingNumber - 1);
            }
            releaseTaskService.save(workRelease);
        }
        if (TaskInforCode.TASK_STATUS_UNCOMMIT.equals(workStuInfo.getTaskStatus())) {
            workStuInfo.setTaskStatus(TaskInforCode.TASK_STATUS_PENDING);
        }
        workStuInfo.setResult(result);
        Long userId = workStuInfo.getStuId();
        workStuInfo = taskStuInforRepository.save(workStuInfo);
        return workStuInfo;
    }
    public List<TaskStuInfor> findAllByReleaseTaskId(String releaseTaskId) {
        return taskStuInforRepository.findAllByReleaseTaskIdAndDeleteFlagOrderByStuIdAsc(releaseTaskId, DataValidity.VALID.getState());
    }

    RowMapper<TaskStuInforDomain> taskStuInfor = new RowMapper<TaskStuInforDomain>() {
        @Override
        public TaskStuInforDomain mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            TaskStuInforDomain domain = new TaskStuInforDomain();
            domain.setId(rs.getString("id"));
            domain.setStuId(rs.getLong("stu_id"));
            domain.setStuName(rs.getString("stu_name"));
            domain.setResult(rs.getString("result"));
            domain.setCommitTime(rs.getDate("commit_time"));
            domain.setJobNum(rs.getString("JOB_NUM"));
            domain.setClassName(rs.getString("class_name"));
            domain.setGrade(rs.getString("grade"));
            domain.setTaskStatus(rs.getString("task_status"));
            return domain;
        }
    };

    public List<TaskStuInforDomain> findTaskInforDomain(TaskInforDoMain domain) {
        String sql = "SELECT tt.id,tt.stu_id,tt.stu_name,tt.result,tt.grade,tt.commit_time,tu.JOB_NUM,tc.`NAME` class_name,tt.task_status FROM t_task_stu_infor tt LEFT JOIN t_user tu ON tu.id=tt.stu_id LEFT JOIN t_course_class tcc ON tt.course_class_id = tcc.id LEFT JOIN t_classes tc ON tc.ID=tcc.CLASS_ID  WHERE tt.delete_flag=0 ";
        String countSql = "SELECT count(*) FROM t_task_stu_infor tt LEFT JOIN t_user tu ON tu.id=tt.stu_id LEFT JOIN t_course_class tcc ON tt.course_class_id = tcc.id LEFT JOIN t_classes tc ON tc.ID=tcc.CLASS_ID  WHERE tt.delete_flag=0 ";
        if (!StringUtils.isEmpty(domain.getReleaseTaskId())) {
            sql += " AND tt.release_task_id= '" + domain.getReleaseTaskId() + "'";
            countSql+=" AND tt.release_task_id= '" + domain.getReleaseTaskId() + "'";
        }
        if (!StringUtils.isEmpty(domain.getTaskStatus())) {
            sql += " and tt.task_status='" + domain.getTaskStatus() + "'";
            countSql += " and tt.task_status='" + domain.getTaskStatus() + "'";
        }
        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("tt.commit_time");
        dto.setAsc(true);
        sort.add(dto);
//        Map<String, Object> pageInfor = pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), taskStuInfor, sort, sql, countSql);
        List<TaskStuInforDomain> info = pageJdbcUtil.getInfo(sql, taskStuInfor);
        return info;
    }

    public List<TaskStuInfor> findAllByReleaseTaskIdAndTaskStatus(String releaseTaskId, String taskStatus) {
        return taskStuInforRepository.findAllByReleaseTaskIdAndTaskStatusAndDeleteFlagOrderByStuIdAsc(releaseTaskId, taskStatus, DataValidity.VALID.getState());
    }

    /**
     * 查看任务提交与未提交数
     *
     * @param releaseTaskId 发布的任务的Id
     * @return
     */
    public TaskNumDoMain getTaskNum(String releaseTaskId) {
        TaskNumDoMain taskNumDoMain = new TaskNumDoMain();
        Integer unCommitNum = taskStuInforRepository.countByReleaseTaskIdAndTaskStatusAndDeleteFlag(releaseTaskId, TaskInforCode.TASK_STATUS_UNCOMMIT, DataValidity.VALID.getState());
        Integer integer = taskStuInforRepository.countByReleaseTaskIdAndDeleteFlag(releaseTaskId, DataValidity.VALID.getState());
        taskNumDoMain.setUnCommitNum(unCommitNum);
        taskNumDoMain.setCommitNum(integer - unCommitNum);
        return taskNumDoMain;
    }

    /**
     * 获取任务下学生的提交情况
     *
     * @param releaseTaskId
     * @return
     */

    public TaskNumDoMain findTaskStatistics(String releaseTaskId) {
        TaskNumDoMain taskNumDoMain = new TaskNumDoMain();
        ReleaseTask byId = releaseTaskService.findById(releaseTaskId);
        if (byId != null) {
            taskNumDoMain.setTotalNum(taskStuInforRepository.countByReleaseTaskIdAndDeleteFlag(releaseTaskId, 0));
            taskNumDoMain.setCreatTime(byId.getCreatedDate());
            taskNumDoMain.setTaskName(byId.getTaskName());
            taskNumDoMain.setScoringMethod(byId.getScoringMethod());
            Classes aClass = classesService.findClass(byId.getClassId());
            if (aClass != null) {
                taskNumDoMain.setClassName(aClass.getName());
            }
            taskNumDoMain.setUnCommitNum(taskStuInforRepository.countByReleaseTaskIdAndTaskStatusAndDeleteFlag(releaseTaskId, TaskInforCode.TASK_STATUS_UNCOMMIT, 0));
            taskNumDoMain.setCommitNum(byId.getCommitNum());
            taskNumDoMain.setApprovedNum(taskStuInforRepository.countByReleaseTaskIdAndTaskStatusAndDeleteFlag(releaseTaskId, TaskInforCode.TASK_STATUS_APPROVED, 0));
            return taskNumDoMain;
        }
        return null;
    }

    RowMapper<RankNumDomain> rankRm = new RowMapper<RankNumDomain>() {

        @Override
        public RankNumDomain mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            RankNumDomain domain = new RankNumDomain();
            domain.setRank(rs.getString("result"));
            domain.setRandNum(rs.getInt("num"));
            return domain;
        }
    };
    RowMapper<EasyWrongTopic> errList = new RowMapper<EasyWrongTopic>() {

        @Override
        public EasyWrongTopic mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            EasyWrongTopic domain = new EasyWrongTopic();
            domain.setOrderNum(rs.getInt("order_num"));
            domain.setReleaseQuestionId(rs.getString("ID"));
            domain.setErrorType(rs.getInt("error_type"));
            return domain;
        }
    };

    public List<EasyWrongTopic> getQuestionErrorList(String releaseTaskId, Long stuId) {
        String sql = "SELECT tq.ID,tq.order_num,tt.error_type FROM t_release_task_question tq LEFT JOIN t_task_stu_answer tt ON tq.ID=tt.release_question_id WHERE tt.delete_flag=0 AND tq.release_task_id ='" + releaseTaskId + "' AND tt.stu_id=" + stuId + " AND tt.is_correct=0 ORDER BY tq.order_num ASC";
        return pageJdbcUtil.getInfo(sql, errList);
    }

    public List<RankNumDomain> getTaskRank(String releaseTaskId) {
        List<RankNumDomain> list=new ArrayList<>();
        String sql = "SELECT t.result result,COUNT(*) num FROM t_task_stu_infor t WHERE t.release_task_id= '" + releaseTaskId + "' and t.commit_time is not null GROUP BY t.result";
        Integer integer = taskStuInforRepository.countByReleaseTaskIdAndDeleteFlagAndCommitTimeIsNull(releaseTaskId, DataValidity.VALID.getState());
        RankNumDomain rankNumDomain = new RankNumDomain();
        rankNumDomain.setRank("未提交");
        rankNumDomain.setRandNum(integer);
        list.add(rankNumDomain);
        list.addAll(pageJdbcUtil.getInfo(sql, rankRm));
        return list;
    }

    public int updateIsShowAnswer(String taskStuInforId, String isShowAnswer) {
        TaskStuInfor byId = taskStuInforRepository.findById(taskStuInforId);
        if (byId != null) {
            byId.setIsShowAnswer(isShowAnswer);
            taskStuInforRepository.save(byId);
            return 1;
        }
        return 0;
    }
    public Integer updateIsShowGrade(String taskStuInforId, String isShowGrade) {
        TaskStuInfor byId = taskStuInforRepository.findById(taskStuInforId);
        if (byId != null) {
            byId.setIsShowGrade(isShowGrade);
            taskStuInforRepository.save(byId);
            return 1;
        }
        return 0;
    }
    public Integer countByReleaseTaskId(String releaseTaskId) {
        return taskStuInforRepository.countByReleaseTaskIdAndDeleteFlag(releaseTaskId, DataValidity.VALID.getState());
    }
    public Integer countUnCommitNum(Long stuId) {
        return taskStuInforRepository.countByStuIdAndTaskStatusAndDeleteFlag(stuId, TaskInforCode.TASK_STATUS_UNCOMMIT, DataValidity.VALID.getState());
    }

//	  public TaskStuInfor approveStuTask(String workStuInfoId, String result, List<String> comment, List<String> id, boolean isAuto, String teacherName) {
//	        WorkStuInfo workStuInfo = workStuInfoRespository.findByIdAndDeleteFlag(workStuInfoId, DeleteSign.NORMAL.getIntValue());
//	        String workReleaseId = workStuInfo.getWorkRelease().getId();
//	        List<StuAnswer> stuAnswers = new ArrayList<>();
//	        List<StuAnswer> stuAnswerList = stuAnswerService.findByIdIn(id);
//	        if (null != stuAnswerList) {
//	            for (int i = 0; i < id.size(); i++) {
//	                for (StuAnswer stAnswer : stuAnswerList) {
//	                    if (stAnswer.getId().equals(id.get(i))) {
//	                        if (comment != null) {
//	                            if (comment.get(i) != null) {
//	                                stAnswer.setComment(comment.get(i));
//	                            }
//	                        }
//	                        stAnswer.setBatchTime(new Date());
//	                        stuAnswers.add(stAnswer);
//	                    }
//	                }
//	            }
//	        }
//	        if (!stuAnswers.isEmpty()) {
//	            stuAnswerService.saveStuAnswer(stuAnswers);
//	        }
//	        Date date = new Date();
//	        workStuInfo.setBatchTime(date);
//	        PushMessage msg = new PushMessage();
//	        WorkRelease workRelease = workReleaseService.findById(workReleaseId);
////			String workSource = "";
//	        if (workStuInfo.getResult() == null || "".equals(workStuInfo.getResult())) {
//	            Integer pendingNumber = workRelease.getPendingNumber();
//	            if (pendingNumber == null) {
//	                pendingNumber = 0;
//	            }
//	            if (pendingNumber > 0) {
//	                workRelease.setPendingNumber(pendingNumber - 1);
//	            }
//	            workReleaseService.saveWorkRelease(workRelease);
//	        }
//	        String groupId = workStuInfo.getGroupId();
//	        if (!StringUtils.isEmpty(groupId)) {
//	            GroupInfo groupInfo = groupInfoRespository.findByIdAndDeleteFlag(groupId, DeleteSign.NORMAL.getIntValue());
//	            if (groupInfo != null) {
//	                msg.setTeachingClassName(groupInfo.getName());
//	            }
//	        }
//	        msg.setHomeWorkName(workRelease.getWorkName());
//	        msg.setHomeWorkResult(result);
//	        msg.setWorkStuId(workStuInfo.getId());
//	        msg.setWorkReleaseId(workReleaseId);
//	        if (workStuInfo.getWhetherCommit() == 0) {
//	            workStuInfo.setWhetherCommit(1);
//	        }
//	        workStuInfo.setResult(result);
//	        Long userId = workStuInfo.getStuId();
//	        PushMsgThread thread = new PushMsgThread(msg, userId, teacherName);
//	        thread.start();
//	        workStuInfo = workStuInfoRespository.save(workStuInfo);
//	        return workStuInfo;
//	    }
}
